// cpp/imageCache/ImageFileCache.h
//
// Created on 2024/8/21.
//
// Node APIs are not fully supported. To solve the compilation error of the interface cannot be found,
// please include "napi/native_api.h".

#ifndef IMAGECACHEDEMO_IMAGEFILECACHE_H
#define IMAGECACHEDEMO_IMAGEFILECACHE_H
#include <map>
#include <vector>
#include <string>
#include <napi/native_api.h>
#include <arkui/native_node.h>
#include <node_api_types.h>
#include <mutex>
#include "RemoteCommunicationKit/rcp.h"
#include "ImageUtil.h"
#include "LRUCache.h"

class ImageFileCache {
public:
    static ImageFileCache *GetInstance();
    void InitCache(const std::string &cacheDir, size_t cacheSize, napi_env env, napi_callback_info info);
    void Preload(const std::string &loadSrc, const std::string &signature = "");
    std::string GetImageCache(const std::string &loadSrc, ArkUI_NodeHandle image);
    void ResponseCallbackFunc(const char *buffer, size_t buffer_size, const std::string &loadSrc);
    void CancelRequest(std::string loadSrc);
    std::map<std::string, std::pair<Rcp_Session *, Rcp_Request *>> sessionRequestMap;
    static std::mutex sessionMutex;

private:
    ImageFileCache() {}
    void AddFileCacheMap(const std::string loadSrc, size_t bufferSize);
    void DownloadFetch(std::string src, size_t *bufferSize);
    void SetImageFileCacheDir(const std::string &cacheDir);
    void FileDelete(const std::string &fileKey);
    void FileSave(const char *buffer, const size_t &bufferSize, const std::string &loadSrc);
    static void UpdateNativeImage(const std::string &loadSrc);
    static void hm_threadsafe_func(napi_env env, napi_value js_fun, void *context, void *data);
    static const std::string GetSandBoxPath(const std::string &fileKey);
    static const std::string GetFullFilePatchInCache(const std::string &loadSrc);
    static LRUCache lruCache;
    static ImageUtil util;
    static std::string cacheDir;
    static std::map<std::string, std::vector<ArkUI_NodeHandle>> imageHandlesWaitList;
    static napi_threadsafe_function g_cache_callback_handle;
    static ImageFileCache *instance;
    std::map<std::string, bool> g_on_flight;
    std::mutex onflightMutex;
};

struct Rcp_ResponseCallback_UserCtxt {
    ImageFileCache *imageCache_userCtxt;
    std::string userCtxt_url;
    Rcp_ResponseCallbackObject *responseCallbackObject;
};

#endif // IMAGECACHEDEMO_IMAGEFILECACHE_H
